package com.diandian.backend.meituan.shangou.exchange.service;

import com.alibaba.fastjson.JSON;
import com.diandian.backend.meituan.shangou.exchange.client.DianDianStoreClient;
import com.diandian.backend.meituan.shangou.exchange.client.dto.MeituanShangouStoreDetailOpenApiParamDTO;
import com.diandian.backend.meituan.shangou.exchange.client.dto.StoreMeituanShangouStoreInfoDetailOpenApiResp;
import com.diandian.backend.meituan.shangou.exchange.req.GetProductSkuInfoReq;
import com.diandian.backend.meituan.shangou.exchange.req.SkuStockUpdateOneReq;
import com.diandian.backend.meituan.shangou.exchange.resp.BusinessGetProductSkuInfoResp;
import com.diandian.base.boot.starter.exception.DefaultException;
import com.diandian.base.boot.starter.response.BaseResult;
import com.diandian.meituan.shangou.boot.starter.dto.product.store.StoreProductUpdateSkuStockDTO;
import com.diandian.meituan.shangou.boot.starter.response.QueryStoreProductSkuInfoResponse;
import com.diandian.meituan.shangou.boot.starter.response.QueryStoreProductSkuInfoResponseSuccessList;
import com.diandian.meituan.shangou.boot.starter.response.StoreProductBatchUpdateSkuStockResponse;
import com.diandian.meituan.shangou.boot.starter.response.product.store.QueryStoreProductDetailResponse;
import com.diandian.meituan.shangou.boot.starter.service.MeituanProductStoreService;
import com.diandian.meituan.shangou.boot.starter.service.MeituanProductStoreSkuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class BusinessSkuStockManageService {

    private static final Logger logger = LoggerFactory.getLogger(BusinessSkuStockManageService.class);

    @Autowired
    private MeituanProductStoreService meituanProductService;

    @Autowired
    private MeituanProductStoreSkuService meituanProductStoreSkuService;

    @Autowired
    private DianDianStoreClient dianDianStoreClient;

    /**
     * 查询商品库存信息
     * @param appKey
     * @param appSecret
     * @param belong
     * @param data
     * @return
     */
    public List<BusinessGetProductSkuInfoResp> getProductSkuStockInfo(String appKey, String appSecret, String belong, GetProductSkuInfoReq data){

        data.check();

        String offlineStoreCode = data.getOfflineStoreCode();
        String onlineStoreCode = data.getOnlineStoreCode();
        String productCode = data.getProductCode();
        String skuCode = data.getSkuCode();

        String storeCode;
        if(onlineStoreCode == null || "".equals(onlineStoreCode)){
            storeCode = offlineStoreCodeToOnlineStoreCode(belong, offlineStoreCode);
        } else {
            storeCode = onlineStoreCode;
        }

        QueryStoreProductSkuInfoResponse response = meituanProductStoreSkuService.getProductSkuInfo(appKey, appSecret, storeCode, productCode, skuCode);
        if(response == null){
            throw new DefaultException("查询库存异常");
        }
        if(response.getSuccess_list() == null || response.getSuccess_list().size() == 0 || response.getResult_code() != 1){
            throw new DefaultException("未查到库存数据");
        }

        List<BusinessGetProductSkuInfoResp> result = new ArrayList<>();

        List<QueryStoreProductSkuInfoResponseSuccessList> skuData = response.getSuccess_list();
        for (int i = 0; i < skuData.size(); i++) {
            BusinessGetProductSkuInfoResp item = new BusinessGetProductSkuInfoResp();
            Long stock = skuData.get(i).getStock() == null ? null : Long.parseLong(skuData.get(i).getStock());
            item.setInQty(stock);
            item.setOnlineStoreCode(onlineStoreCode);
            item.setOfflineStoreCode(offlineStoreCode);
            item.setProductCode(productCode);
            item.setSkuCode(skuCode);
            item.setLastModificationTime(new Date());
            result.add(item);
        }

        return result;
    }


    /**
     * 同步单个商品库存
     * @param data
     * @throws Exception
     */
    public StoreProductBatchUpdateSkuStockResponse skuStockUpdateOne(String appKey, String appSecret, String belong, SkuStockUpdateOneReq data) throws Exception {

        // 1. 参数检查
        if (!data.check()) {
            logger.info("更新单个库存时参数缺失，数据：{}", JSON.toJSONString(data));
            throw new DefaultException(1, "更新单个库存时参数缺失");
        }
        String offlineStoreCode = data.getOfflineStoreCode();
        String onlineStoreCode = data.getOnlineStoreCode();
        String productCode = data.getProductCode();
        String skuCode = data.getSkuCode();
        int stockCount = data.getStockCount() < 0 ? 0 : data.getStockCount();
        data.setStockCount(stockCount);

        // 2. 门店编码处理：有线上编码优先使用线上编码，否则使用线下门店编码兑换线上编码
        String targetStoreCode = "";
        if(onlineStoreCode != null && !"".equals(onlineStoreCode)){
            targetStoreCode = onlineStoreCode;
        } else {
            targetStoreCode = offlineStoreCodeToOnlineStoreCode(belong, offlineStoreCode);
        }

        // 3. 查询线上门店是否有此商品，无则停止同步
        QueryStoreProductDetailResponse response = meituanProductService.getStoreProductDetail(appKey, appSecret, targetStoreCode, productCode);
        if(response.getSuccess_map() == null || response.getSuccess_map().getApp_spu_code() == null || "".equals(response.getSuccess_map().getApp_spu_code())) {
            logger.info("更新单个库存时门店无商品不存在，数据：{}", JSON.toJSONString(data));
            throw new DefaultException("更新单个库存时门店无商品不存在");
        }

        // 4. 执行同步操作
        StoreProductUpdateSkuStockDTO dto = new StoreProductUpdateSkuStockDTO();
        dto.setAppPoiCode(onlineStoreCode);
        dto.setAppSpuCode(productCode);
        dto.setSkuId(skuCode);
        dto.setStock(String.valueOf(stockCount));
        StoreProductBatchUpdateSkuStockResponse pushResponse = meituanProductStoreSkuService.singleUpdateSkuStock(appKey, appSecret, dto);
        logger.info("更新单个商品库存，数据：{}, 执行结果：{}", JSON.toJSONString(data), JSON.toJSONString(pushResponse));

        return pushResponse;
    }

    /**
     * 将美团线下门店编码转为线上门店编码
     * @param offlineStoreCode
     * @return
     */
    private String offlineStoreCodeToOnlineStoreCode(String belong, String offlineStoreCode) {
        MeituanShangouStoreDetailOpenApiParamDTO paramDTO = new MeituanShangouStoreDetailOpenApiParamDTO();
        paramDTO.setOfflineCode(offlineStoreCode);
        paramDTO.setBelong(belong);
        BaseResult<StoreMeituanShangouStoreInfoDetailOpenApiResp> baseResult = dianDianStoreClient.getMeituanShanGouStoreDetail(paramDTO);


        if(baseResult == null || baseResult.getCode() != 0 || baseResult.getData() == null){
            throw new DefaultException("未找到此门店");
        }

        StoreMeituanShangouStoreInfoDetailOpenApiResp detailResp = baseResult.getData();
        if(detailResp == null || detailResp.getOnlineCode() == null || "".equals(detailResp.getOnlineCode())){
            throw new DefaultException("未找到此门店");
        }

        return detailResp.getOnlineCode();
    }
}
